/*
 * Copyright 2007 Dan Hodge
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.datajanitor.baja.spi.data;

import java.io.Serializable;
import java.util.Date;

import net.datajanitor.baja.data.UserInfo;
import net.datajanitor.baja.spi.support.UrlBuilder;

/**
 * Contains the authentication information for an authenticated user. 
 */
public class AuthInfo implements Serializable {
    private static final long serialVersionUID = -145517120515420677L;
    private String authToken;
    private UserInfo user;
    private Date timestamp;
    
    public AuthInfo(UserInfo user, String authToken) {
        this.authToken = authToken;
        this.user = user;
        this.timestamp = new Date();
    }
    
    public UserInfo getUser() {
        return this.user;
    }
    
    public void invalidate() {
        this.authToken = null;
        this.user = null;
    }
    
    public boolean isAuthenticated() {
        return (this.authToken != null && this.user != null);
    }
    
    /**
     * 
     * @param interval
     * @return true if this auth info has timed out, false if not
     */
    public boolean checkTimeout(long interval) {
        long diff = System.currentTimeMillis() - this.timestamp.getTime();
        return diff > interval;
    }
    
    public String getAuthToken() {
        return this.authToken;
    }
    
    public UrlBuilder bindParameter(UrlBuilder builder, String name) {
        builder.addParam(name, this.authToken);
        return builder;
    }
    
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append(getClass().getName()).append("[user=").append(getUser()).append(",authenticated=")
               .append(isAuthenticated()).append(",timestamp=").append(this.timestamp).append("]");
        
        return builder.toString();
    }
}
